package com.jt.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.service.UserService;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.jsonwebtoken.SignatureAlgorithm;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class JwtUtil {

    @Autowired
    private UserMapper userMapper;

    // 设置token过期时间
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    private static final String TOKEN_MIYAO = "asfhwkwewrkjwerwr";

    //生成 token
    public   String getToken(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        JwtBuilder builder = Jwts.builder();
        builder.setExpiration(new Date(System.currentTimeMillis() + EXPIRE));
        builder.addClaims(map);
        builder.signWith(SignatureAlgorithm.HS256, TOKEN_MIYAO);
        return builder.compact();
    }

    /*解析TOKEN,将token对象转换成LoginUser*/
    public   User tokenAsUser(String token) {
        Jwt parse = Jwts.parser().setSigningKey(TOKEN_MIYAO).parse(token);
        Map<String, Object> body = (Map<String, Object>) parse.getBody();
        String id = body.get("id").toString();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", id));
        return user;
    }

}
